package com.kinon.tyjaccount.view;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.adapter.CaidandetailAdapter;
import com.kinon.tyjaccount.data.UPacketFactory;
import com.kinon.tyjaccount.entity.CaidanEntity;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.kinon.tyjaccount.tools.Utility;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.IReceiveCallback;
import sunmi.ds.data.DSData;
import sunmi.ds.data.DSFile;
import sunmi.ds.data.DSFiles;
import sunmi.ds.data.DataPacket;

public class JiesuanActivity extends Activity {
	
	private TextView tv_shuliang;
	private TextView tv_heji;
	private ListView lv_caidan;
	private TextView tv_fanhui;
	private EditText et_pay;
	String id;
	String token;
	String total;
	
	private static CaidandetailAdapter caidandetailAdapter;
	/**获得数据*/
	static ArrayList<CaidanEntity> infolist;
	HttpTools httptools=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jiesuan);
		initRes();
	}

	private void initRes() {
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		tv_shuliang=(TextView)findViewById(R.id.tv_shuliang);
		tv_heji=(TextView)findViewById(R.id.tv_heji);
		lv_caidan=(ListView)findViewById(R.id.lv_caidan);
		tv_fanhui=(TextView)findViewById(R.id.tv_fanhui);
		et_pay=(EditText)findViewById(R.id.et_pay);
		tv_fanhui.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		et_pay.requestFocus();
		et_pay.addTextChangedListener(watcher);
//		et_pay.setEnabled(false);
//		handler.postDelayed(runnable, 1000);
		Caidan();

	}

	private void Show(){
		DSKernel mDSKernel = DSKernel.newInstance();
		mDSKernel.init(getApplicationContext(), new IConnectionCallback() {
			@Override
			public void onDisConnect() {

			}

			@Override
			public void onConnected(ConnState state) {

			}
		});
		mDSKernel.addReceiveCallback(new IReceiveCallback() {
			@Override
			public void onReceiveData(DSData data) {

			}

			@Override
			public void onReceiveFile(DSFile file) {

			}

			@Override
			public void onReceiveFiles(DSFiles files) {

			}

			@Override
			public void onReceiveCMD(DSData cmd) {

			}
		});
		JSONObject json = new JSONObject();
		try {
			json.put("title", "请支付：");
			json.put("content","￥ "+total);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		DataPacket packet = UPacketFactory.buildShowText(DSKernel.getDSDPackageName(), json.toString(),null);
		mDSKernel.sendData(packet);
	}

	private void Caidan() {
		if(NetWorkUtil.isNetwork(getApplicationContext())==false)
		{
			ToastUtil toastUtil=new ToastUtil();
			toastUtil.Short(getApplicationContext(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
			return;
		}
		infolist=new ArrayList<CaidanEntity>();
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		String token = sp.getString("data", "");
		String orderid = getIntent().getStringExtra("orderid");
		if (httptools == null) {
			httptools = new HttpTools(getApplicationContext());
		}
		httptools.getDetail(token, orderid,"","",new JsonCaidan());

	}

	public class JsonCaidan extends JsonHttpResponseHandler {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			try {
				Log.i("zq",response.toString());
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code == true) {
					Log.i("zq", "订单详情---"+response.toString());
					JSONObject object = response.getJSONObject("data");
					id = object.getString("id");
					total = object.getString("total");
					String totalamount = object.getString("totalamount");
					JSONArray array = object.getJSONArray("details");
					for (int j = 0;j < array.length(); j++) {					
						JSONObject details = array.getJSONObject(j);
						String caipinid = details.getString("id");
						String name = details.getString("name");
						String amount = details.getString("amount");
						String price = details.getString("price");
						infolist.add(new CaidanEntity(caipinid, amount, name, price, 1));							
					}
					Show();
					tv_shuliang.setText(totalamount);
					tv_heji.setText(total);
					caidandetailAdapter = new CaidandetailAdapter(getApplicationContext(), infolist);
					lv_caidan.setAdapter(caidandetailAdapter);
					lv_caidan.setDivider(null);
					Utility.setListViewHeightBasedOnChildren(lv_caidan);
				}else {
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
//	private Handler handler = new Handler();
//	private Runnable runnable = new Runnable() {
//		public void run() {
//			try {
//				this.update();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			handler.postDelayed(this, 1000);// 间隔60秒刷新一次
//		}
//		void update() throws IOException {
////			onrefresh.onPullDownToRefresh(list_order);
//			if (et_pay.getText().length()==17) {
//				Dingdan();
//				handler.removeCallbacks(runnable);
////				Toast.makeText(JiesuanActivity.this, "成功", Toast.LENGTH_SHORT).show();
//			}else {
//				Log.i("info", "-----"+et_pay.getText().length());
//			}
//			
//		}
//	}; 
	private void Dingdan() {
		if(NetWorkUtil.isNetwork(getApplicationContext())==false)
		{
			ToastUtil toastUtil=new ToastUtil();
			toastUtil.Short(getApplicationContext(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
			et_pay.setText("");
			return;
		}
//		Log.e("info", "et_id---" + et_pay.getText().toString());
		if (httptools == null) {
			httptools = new HttpTools(JiesuanActivity.this);
		}
		String str = et_pay.getText().toString().trim();
		httptools.otherPay(token, id,str.substring(0, 16),new JsonDingdan());	
	}
	public class JsonDingdan extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			Log.i("info", "jiesuan---"+response.toString());
			try {
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if(code==true){
//					et_pay.setText("");
//					handler.removeCallbacks(runnable);
					Toast.makeText(JiesuanActivity.this, msg, Toast.LENGTH_SHORT).show();
					finish();
				}else{
//					handler.postDelayed(runnable, 1000);
					et_pay.setText("");
					Toast.makeText(JiesuanActivity.this, msg, Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
	}
private TextWatcher watcher = new TextWatcher() {
	    
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
//	    	Toast.makeText(getActivity(), "2", 1).show();
	        
	    }
	    
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	        // TODO Auto-generated method stub
//	    	Toast.makeText(getActivity(), "3", 1).show();
	        
	    }
	    
	    @Override
	    public void afterTextChanged(Editable s) {
//	    	Toast.makeText(getActivity(), "4", 1).show();
	    	if (et_pay.getText().toString().trim().length()==16) {
//	    		Toast.makeText(getActivity(), "5", 1).show();
//	    		Intent intent = new Intent();
//				intent.putExtra("orderid", et_id.getText().toString());
//				intent.setClass(getActivity(), DingdandetialerweimaActivity.class);				
//				startActivity(intent);
//				et_id.setText("");
//				Toast.makeText(getActivity(), "成功", Toast.LENGTH_SHORT).show();
	    		Dingdan();
			}
	        
	        
	    }
	};
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
	       super.onWindowFocusChanged(hasFocus);
	       if (hasFocus) {
	            View decorView = getWindow().getDecorView();
	                 decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
	                  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
	                  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
	                  |View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 
	                  |View.SYSTEM_UI_FLAG_FULLSCREEN);
	               }
	}
}
